package com.atxiaodei.kabudarpc.handler;

import com.atxiaodei.kabudarpc.bean.RpcRequest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName Mediator
 * @Deacription TODO
 * @Author 卡布达
 * @Date 2021/10/31 15:52
 * @Version 1.0
 **/
public class Mediator {
    public static Map<String,BeanMethod> map=new ConcurrentHashMap<>();

    public volatile static Mediator instance;

    private Mediator(){

    }
    // 单例模式
    public static Mediator getInstance(){
        if (instance==null) {
            synchronized (Mediator.class){
                if (instance==null){
                    instance=new Mediator();
                }
            }
        }
        return instance;
    }

    public Object process(RpcRequest rpcRequest) throws InvocationTargetException, IllegalAccessException {
        String key=rpcRequest.getClassName()+"."+rpcRequest.getMethodName();
//        通过key获取唯一的实例，通过反射调用返回
        BeanMethod beanMethod = map.get(key);

        Object bean = beanMethod.getBean();
        Method method = beanMethod.getMethod();

        Object object = method.invoke(bean, rpcRequest.getArgs());
        return object;

    }
}
